package com.css.fxfzypg.modules.auxiliaryDecisionManage.auxiliaryDecision.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.css.fxfzypg.base.attachment.entity.AttachmentInfoEntity;
import com.css.fxfzypg.base.attachment.service.AttachmentInfoService;
import com.css.fxfzypg.constants.FxfzConstants;
import com.css.fxfzypg.modules.auxiliary.repository.AuxiliaryMapRepository;
import com.css.fxfzypg.modules.auxiliaryDecisionManage.auxiliaryDecision.entity.AuxiliaryDecision;
import com.css.fxfzypg.modules.auxiliaryDecisionManage.auxiliaryDecision.entity.AuxiliaryDecisionReport;
import com.css.fxfzypg.modules.auxiliaryDecisionManage.auxiliaryDecision.entity.DisasterScenario;
import com.css.fxfzypg.modules.auxiliaryDecisionManage.auxiliaryDecision.entity.EmergencyResponse;
import com.css.fxfzypg.modules.auxiliaryDecisionManage.auxiliaryDecision.param.AuxiliaryDecisionParam;
import com.css.fxfzypg.modules.auxiliaryDecisionManage.auxiliaryDecision.repository.AuxiliaryDecisionRepository;
import com.css.fxfzypg.modules.auxiliaryDecisionManage.auxiliaryDecision.service.AuxiliaryDecisionService;
import com.css.fxfzypg.modules.auxiliaryDecisionManage.auxiliaryDecision.vo.AreaResultVO;
import com.css.fxfzypg.modules.baseData.entity.DisasterScene;
import com.css.fxfzypg.modules.baseData.entity.ErcmEntity;
import com.css.fxfzypg.modules.baseData.entity.HisPrEntity;
import com.css.fxfzypg.modules.maps.service.SetEarthquakeMapService;
import com.css.fxfzypg.modules.similitudeAnalyse.consts.AreaConsts;
import com.css.fxfzypg.modules.similitudeAnalyse.entity.RealEarthquakeEntity;
import com.css.fxfzypg.modules.similitudeAnalyse.entity.RealSeismicInfluenceflied;
import com.css.fxfzypg.modules.similitudeAnalyse.repository.SimAnalyseRepository;
import com.css.fxfzypg.modules.similitudeAnalyse.service.SimAnalyseService;
import com.css.fxfzypg.modules.similitudeAnalyse.utils.ListUtil;
import com.css.fxfzypg.modules.similitudeAnalyse.utils.Xml2ObjectUtil;
import com.css.fxfzypg.modules.suggestinfo.manage.disasterscenarioManage.repository.DisasterScenarioManageRepository;
import com.css.fxfzypg.modules.suggestinfo.manage.disasterscenarioManage.repository.entity.DisasterScenarioManageEntity;
import com.css.fxfzypg.modules.suggestinfo.manage.emergencydisasterManage.repository.entity.EmergencyDisasterManageEntity;
import com.css.fxfzypg.modules.suggestinfo.manage.emergencydisposalManage.repository.EmergencyDisposalManageRepository;
import com.css.fxfzypg.modules.suggestinfo.manage.emergencydisposalManage.repository.entity.EmergencyDisposalManageEntity;
import com.css.fxfzypg.modules.test.CustomXWPFDocument;
import com.css.fxfzypg.util.*;
import com.css.fxfzypg.web.PlatformSessionContext;
import com.css.fxfzypg.zcpt.sys.service.SysAreaService;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.data.PictureRenderData;
import com.deepoove.poi.plugin.table.HackLoopTableRenderPolicy;
import com.deepoove.poi.xwpf.NiceXWPFDocument;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: zhangSongRui
 * @CreateTime: 2023/03/23
 * @Description: 震后辅助决策管理
 */
@Service
public class AuxiliaryDecisionServiceImpl implements AuxiliaryDecisionService {

    @Resource
    private AuxiliaryDecisionRepository auxiliaryDecisionRepository;
    @Resource
    private SetEarthquakeMapService setEarthquakeMapService;

    private static final String URL = "http://1.eqweixin.sinaapp.com/zxml.php";

    @Resource
    private AttachmentInfoService attachmentInfoService;

    @Resource
    SimAnalyseService SimAnalyseService;
    @Value("${file.upload.path}")
    private String localDir;

    @Resource
    SimAnalyseRepository simAnalyseRepository;

    @Resource
    SysAreaService sysAreaService;
    @Resource
    DisasterScenarioManageRepository disasterScenarioManageRepository;

    @Resource
    EmergencyDisposalManageRepository emergencyDisposalManageRepository;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private AuxiliaryMapRepository auxiliaryMapRepository;

    //写入数据
    @Override
    public void writeData(RealEarthquakeEntity realEntity) {
        //获取最新数据列表
        // List<RealEarthquakeEntity> realList = Xml2ObjectUtil.getRealEarthquakeEntity(URL);
        ArrayList<AuxiliaryDecision> list = new ArrayList<>();
        //如果为国内的
        String s = setEarthquakeMapService.queryProvinceCityCountyNameStringByLonLat(realEntity.getEpiLon(), realEntity.getEpiLat());
        if (!StringUtils.isEmpty(s)) {
            //判断该数据是否存在
            String id = auxiliaryDecisionRepository.getDataByCataId(realEntity.getCataId());
            //如果不存在则新增该数据
            if (StringUtils.isEmpty(id)) {
                AuxiliaryDecision auxiliaryDecision = new AuxiliaryDecision();
                //id
                auxiliaryDecision.setId(UUID.randomUUID().toString().replaceAll("-", ""));
                //时间戳
                auxiliaryDecision.setCataId(realEntity.getCataId());
                //发震时间
                Date date = PlatformDateUtils.parseDate(realEntity.getOTime());
                long time = date.getTime();
                //long time = date.getTime() + 8000 * 60 * 60;//给时间加8小时
                date.setTime(time);
                auxiliaryDecision.setEarthquakeTime(date);
                //震级
                auxiliaryDecision.setMagnitude(realEntity.getM());
                //经度
                auxiliaryDecision.setLongitude(realEntity.getEpiLon());
                //维度
                auxiliaryDecision.setLatitude(realEntity.getEpiLat());
                String[] split = s.split(",");
                //省名称
                auxiliaryDecision.setProvince(split[0]);
                //市名称
                auxiliaryDecision.setCity(split[1]);
                //县名称
                auxiliaryDecision.setPrefecture(split[2]);
                //震源深度
                auxiliaryDecision.setSourceDepth(realEntity.getEpiDepth());
                //"云南大理州永平县", - 参考位置：position
                auxiliaryDecision.setLocation(realEntity.getLocationC());
                list.add(auxiliaryDecision);
            }
        }
        if (list.size() != 0) {
            //批量入库
            auxiliaryDecisionRepository.batchSave(list);
        }
    }

    @Override
    public Map<String, Object> getPage(int curPage, int pageSize, AuxiliaryDecisionParam param) {
        return auxiliaryDecisionRepository.getPage(curPage, pageSize, param);
    }

    //灾害情景分析修改
    @Override
    public void updateErcmEntityById(AuxiliaryDecision param) {
        auxiliaryDecisionRepository.updateErcmEntityById(param);
    }

    //应急处置对策修改
    @Override
    public void updateDisasterSceneById(AuxiliaryDecision param) {
        auxiliaryDecisionRepository.updateDisasterSceneById(param);
    }

    //根据id查询
    @Override
    public AuxiliaryDecision findById(String id) {
        AuxiliaryDecision byId = auxiliaryDecisionRepository.findById(id);
        if (StringUtils.isEmpty(byId.getBuildingDamage())) {
            //***根据省市县获取初始灾害情景***/
            DisasterScene disasterScene = auxiliaryDecisionRepository.getDisasterScenario(byId.getProvince(), byId.getCity(), byId.getPrefecture());
            if (null != disasterScene) {
                //建筑物破坏
                byId.setBuildingDamage(disasterScene.getDsDestroy());
                //人员伤亡
                byId.setCasualties(disasterScene.getDsCasualty());
                //地质灾害
                byId.setGeologicHazard(disasterScene.getDsGeology());
                //次生灾害
                byId.setSecondaryDisaster(disasterScene.getDsSecondary());
                //震后交通
                byId.setEarthquakeTraffic(disasterScene.getDsTraffic());
                //其他灾害情景
                byId.setOtherDisaster(disasterScene.getDsElse());
            }
        }
        if (StringUtils.isEmpty(byId.getRfasi())) {
            //***根据省市县获取初始应急处理对策***/
            ErcmEntity emeEntity = auxiliaryDecisionRepository.getEmergencyDisaster(byId.getProvince(), byId.getCity(), byId.getPrefecture());
            if (null != emeEntity) {
                //救援力量和物资投入
                byId.setRfasi(emeEntity.getErcmRfasi());
                //地震灾害危重区域识别
                byId.setEdcai(emeEntity.getErcmEdcai());
                //交通系统保障和抢修
                byId.setTssAer(emeEntity.getErcmTssAer());
                //通信系统保障和抢修
                byId.setAssAer(emeEntity.getErcmAssAer());
                //电力系统保障和抢修
                byId.setPssAer(emeEntity.getErcmPssAer());
                //重要基础设施隐患排查
                byId.setTmir(emeEntity.getErcmTmir());
                //气候特征应对
                byId.setClimateCr(emeEntity.getErcmClimateCr());
                //民族特征应对
                byId.setNationalCr(emeEntity.getErcmNationalCr());
                //谣言、舆情应对
                byId.setTdwrapo(emeEntity.getErcmTdwrapo());
                //其他地方特征应对
                byId.setOlftdwCr(emeEntity.getErcmOlftdwCr());
            }
        }
        return byId;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> createReport(String id, String attachId) throws Exception {
        AuxiliaryDecision auxiliaryDecision = auxiliaryDecisionRepository.findById(id);
        if (PlatformObjectUtils.isEmpty(auxiliaryDecision)) {
            throw new RuntimeException("查询不到震后辅助决策信息");
        }
        String provinceName=auxiliaryDecision.getProvince();
        //判断是否是东部
        boolean eastFlag = ListUtil.useList(AreaConsts.EAST, provinceName);
        //判断是否是西部
        boolean westFlag = ListUtil.useList(AreaConsts.WEST, provinceName);

        if ((eastFlag && !AreaConsts.compare(new Double(auxiliaryDecision.getMagnitude()), AreaConsts.EAST_MAGNITUDE)) ||
                (westFlag && !AreaConsts.compare(new Double(auxiliaryDecision.getMagnitude()), AreaConsts.WEST_MAGNITUD))) {
                throw new RuntimeException("当前数据:{}" + auxiliaryDecision.getId() + "未满足震级大于等于东部地区4级、西部地区5级！");
        }
            //获取模板信息
        AttachmentInfoEntity attach = attachmentInfoService.getAttach(attachId);
        if (PlatformObjectUtils.isEmpty(attach)) {
            throw new RuntimeException("请先上传震后辅助决策报告模板");
        }
        //文件存放目录
        String fileDirId = attach.getFileDirId();
        //文件相对路径
        String attachPath = attach.getAttachPath();
        String attachName = attach.getAttachName();
        if (!attachName.contains("docx")) {
            throw new RuntimeException("只支持docx格式的模板文件");
        }
        //获取报告所需数据
        Map reportDataMap = getReportData(auxiliaryDecision);
        Map<String, String> resultMap = createReport(reportDataMap, attachPath, fileDirId);
        String fileName = resultMap.get("docxName");
        //创建数据报告记录
        AuxiliaryDecisionReport report = new AuxiliaryDecisionReport();
        String reportId = UUIDGenerator.getUUID();
        String reportName = "震后辅助决策报告.docx";
        report.setId(reportId).setReportPath(localDir).setReportCreateUserId(PlatformSessionContext.getUserID())
                .setReportCreateTime(new Date()).setReportName(reportName).setReportFactName(fileName).setAttachId(attachId);
        auxiliaryDecisionRepository.saveAuxiliaryDecisionReport(report);
        //为辅助决策数据关联报告信息
        auxiliaryDecisionRepository.updateReportIdById(reportId, id);
        Map<String, Object> paramMap = new HashMap<>(2);
        paramMap.put("reportName", reportName);
        paramMap.put("reportId", reportId);
        return paramMap;
    }

    private Map<String, String> createReport(Map<String, Object> paramMap, String attachPath, String fileDirId) {
        // 文件存放根目录
        String rootPath = localDir;
        File dir = new File(rootPath);
        // 文件夹不存在则创建
        if (!dir.exists()) {
            boolean mkdir = dir.mkdir();
        }
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String nowStr = sdf.format(now);
        String desFileName = "震后辅助决策报告" + nowStr + ".docx";
        String docxPath = rootPath + File.separator + desFileName;
        try (InputStream inputStream = new FileInputStream(fileDirId + attachPath)) {
        //try (InputStream inputStream = new FileInputStream("D:\\static\\2024\\辅助决策报告模板.docx")) {
            //渲染表格  动态行
            HackLoopTableRenderPolicy policy = new HackLoopTableRenderPolicy();
            Configure config = Configure.newBuilder()
                    .bind("basicList", policy)
                    .bind("detailsList", policy).build();
            // 通过协查函模板，开始生成电子协查函
            try (
                    XWPFTemplate template = XWPFTemplate.compile(inputStream, config).render(paramMap);
                    OutputStream outDocx = Files.newOutputStream(Paths.get(docxPath))) {
                NiceXWPFDocument xwpfDocument = template.getXWPFDocument();
                // 输出word
                template.getXWPFDocument().write(outDocx);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String, String> map = new HashMap<>(4);
        map.put("docxName", desFileName);
        return map;
    }

    private Map getReportData(AuxiliaryDecision auxiliaryDecision) {
        Map<String, Object> map = new HashMap<>();
        //发震时间
        Date earthquakeTime = auxiliaryDecision.getEarthquakeTime();
        Calendar ca = Calendar.getInstance();
        ca.setTime(earthquakeTime);
        //年

        map.put("year", String.valueOf(ca.get(Calendar.YEAR)));
        //月份
        map.put("month", String.valueOf(ca.get(Calendar.MONTH) + 1));
        //日
        map.put("day", String.valueOf(ca.get(Calendar.DAY_OF_MONTH)));
        //时
        map.put("hour", String.valueOf(ca.get(Calendar.HOUR_OF_DAY)));
        //分
        map.put("second", String.valueOf(ca.get(Calendar.MINUTE)));
        //震级
        map.put("magnitude", String.valueOf(auxiliaryDecision.getMagnitude()));
        //经度
        map.put("longitude", String.valueOf(auxiliaryDecision.getLongitude()));
        //纬度
        map.put("latitude", String.valueOf(auxiliaryDecision.getLatitude()));
        //震源深度
        map.put("sourceDepth", String.valueOf(auxiliaryDecision.getSourceDepth()));
        //发震区
        String location = auxiliaryDecision.getLocation();
        map.put("location", location);
        //获取分析结果查询的最新的一条数据
        String id = SimAnalyseService.getNewestSimAnaResultId();
        if (org.apache.commons.lang3.StringUtils.isBlank(id)) {
            throw new RuntimeException("查询不到分析结果");
        }
        Map<String, Object> stringObjectMap = SimAnalyseService.fingById(id);
        HisPrEntity hisPrEntity = null;
        if (PlatformObjectUtils.isNotEmpty(stringObjectMap.get("hisPrEntity"))) {
            hisPrEntity = (HisPrEntity) stringObjectMap.get("hisPrEntity");
        }
        ;
        List<Map<String, Object>> basicList = new ArrayList<>();
        List<Map<String, Object>> detailsList = new ArrayList<>();
        if (hisPrEntity != null) {
            Map<String, Object> basicMap = new HashMap<String, Object>();
            basicMap.put("longitude", hisPrEntity.getDhpEpicenterLongitude().toString());
            basicMap.put("latitude", hisPrEntity.getDhpEpicenterLatitude().toString());
            basicMap.put("location", hisPrEntity.getDhpLocation());
            basicMap.put("magnitude", hisPrEntity.getDhpMagnitude());
            basicMap.put("area", hisPrEntity.getDhpDiArea());
            basicMap.put("people", hisPrEntity.getDhpDiPeople());
            basicMap.put("gdp", hisPrEntity.getDhpDiGdp());
            basicList.add(basicMap);
            Map<String, Object> detailsMap = new HashMap<String, Object>();
            detailsMap.put("death", hisPrEntity.getDhpEsDeath());
            detailsMap.put("injured", hisPrEntity.getDhpEsInjured());
            detailsMap.put("resNumber", hisPrEntity.getDhpEsResNumber());
            detailsMap.put("assi", hisPrEntity.getDhpNeedEmeAssi());
            detailsMap.put("tentsNum", hisPrEntity.getDhpEsTentsNum());
            detailsList.add(detailsMap);

            String angleStr = setEarthquakeMapService.queryPointAzimuthAngle(auxiliaryDecision.getLongitude().toString(), auxiliaryDecision.getLatitude().toString(),
                    hisPrEntity.getDhpEpicenterLongitude().toString(), hisPrEntity.getDhpEpicenterLatitude().toString());
            //String angle = "84.40123781718196";
            String angle  = new BigDecimal(angleStr).setScale( 0, BigDecimal.ROUND_HALF_UP ).toString();
            if (org.apache.commons.lang3.StringUtils.isNotBlank(angle)) {
                if (new BigDecimal(angle).compareTo(BigDecimal.valueOf(90)) < 0 && new BigDecimal(angle).compareTo(BigDecimal.valueOf(0)) > 0) {
                    map.put("position", "北偏东" + angle + "°");
                } else if (new BigDecimal(angle).compareTo(BigDecimal.valueOf(90)) == 0) {
                    map.put("position", "正北");
                } else if (new BigDecimal(angle).compareTo(BigDecimal.valueOf(90)) > 0 && new BigDecimal(angle).compareTo(BigDecimal.valueOf(180)) < 0) {
                    map.put("position", "北偏西" + (new BigDecimal(angle).subtract(BigDecimal.valueOf(90))) + "°");
                } else if (new BigDecimal(angle).compareTo(BigDecimal.valueOf(180)) == 0) {
                    map.put("position", "正西");
                } else if (new BigDecimal(angle).compareTo(BigDecimal.valueOf(270)) < 0 && new BigDecimal(angle).compareTo(BigDecimal.valueOf(180)) > 0) {
                    map.put("position", "南偏西" + (new BigDecimal(angle).subtract(BigDecimal.valueOf(180))) + "°");
                } else if (new BigDecimal(angle).compareTo(BigDecimal.valueOf(270)) == 0) {
                    map.put("position", "正南");
                } else if (new BigDecimal(angle).compareTo(BigDecimal.valueOf(360)) == 0 || new BigDecimal(angle).compareTo(BigDecimal.valueOf(0)) == 0) {
                    map.put("position", "正东");
                } else if (new BigDecimal(angle).compareTo(BigDecimal.valueOf(360)) < 0 && new BigDecimal(angle).compareTo(BigDecimal.valueOf(270)) > 0) {
                    map.put("position", "南偏东" + (new BigDecimal(360).subtract(new BigDecimal(angle))) + "°");
                }
            }
            BigDecimal distance = auxiliaryDecisionRepository.getDistance(auxiliaryDecision.getLongitude(), auxiliaryDecision.getLatitude(), hisPrEntity.getDhpEpicenterLongitude(), hisPrEntity.getDhpEpicenterLatitude());
            //BigDecimal distance = new BigDecimal(3559656.9239409408);
            map.put("distance", PlatformObjectUtils.isEmpty(distance) ? "" : distance.divide(BigDecimal.valueOf(1000), 2, RoundingMode.HALF_DOWN).toString());
            map.put("earthQuakeLevel", hisPrEntity.getDhpMagnitude());
        }else{
            map.put("earthQuakeLevel", "无");
        }

        map.put("basicList", basicList);
        map.put("detailsList", detailsList);
        //建筑物公里格网分布对比图
        String buildingPicturePath =auxiliaryMapRepository.getMapPictureByCataId(auxiliaryDecision.getCataId(),"1");
        //人口公里格网分布对比图
        String peoplePicturesPath =auxiliaryMapRepository.getMapPictureByCataId(auxiliaryDecision.getCataId(),"2");
        //经济格网分布对比图
        String econPicturesPath =auxiliaryMapRepository.getMapPictureByCataId(auxiliaryDecision.getCataId(),"3");
        //设定XX级地震和实际地震建筑物公里格网分布对比图
        List<Map<String, PictureRenderData>> buildingPictures = new ArrayList<>(2);
        Map<String, PictureRenderData> sdBuildingPictureMap = new HashMap<>();
      //  sdBuildingPictureMap.put("picture", null);


        sdBuildingPictureMap.put("picture", PlatformObjectUtils.isNotEmpty(buildingPicturePath)?new PictureRenderData(553, 391, buildingPicturePath):null);
        buildingPictures.add(sdBuildingPictureMap);
        Map<String, PictureRenderData> factBuildingPictureMap = new HashMap<>();
        factBuildingPictureMap.put("picture", null);
//        factBuildingPictureMap.put("picture", new PictureRenderData(200, 200, "D:\\image\\b1ae30220c8593cfbd4b8cea3bd12ca4.jpg"));
        buildingPictures.add(factBuildingPictureMap);
        map.put("buildingPictures", buildingPictures);
        //设定XX级地震和实际地震人口公里格网分布对比图
        List<Map<String, PictureRenderData>> peoplePictures = new ArrayList<>(2);
        Map<String, PictureRenderData> sdPeoplePictureMap = new HashMap<>();
        sdPeoplePictureMap.put("picture",PlatformObjectUtils.isNotEmpty(peoplePicturesPath)? new PictureRenderData(553, 391, peoplePicturesPath):null);
        peoplePictures.add(sdPeoplePictureMap);
        Map<String, PictureRenderData> factPeoplePictureMap = new HashMap<>();
        //factPeoplePictureMap.put("picture", new PictureRenderData(230, 230, "D:\\image\\2023\\02\\15\\supermap-webprinting-report_1676449506502.png"));
        peoplePictures.add(factPeoplePictureMap);
        map.put("peoplePictures", peoplePictures);
        //设定XX级地震和实际地震经济公里格网分布对比图
        List<Map<String, PictureRenderData>> econPictures = new ArrayList<>(2);
        Map<String, PictureRenderData> sdEconPictureMap = new HashMap<>();
        sdEconPictureMap.put("picture", PlatformObjectUtils.isNotEmpty(econPicturesPath)?new PictureRenderData(553, 391, econPicturesPath):null);
        econPictures.add(sdEconPictureMap);
        Map<String, PictureRenderData> factEconPictureMap = new HashMap<>();
        //factEconPictureMap.put("picture", new PictureRenderData(230, 230, "D:\\image\\2023\\02\\15\\supermap-webprinting-report_1676449634351.png"));
        econPictures.add(factEconPictureMap);
        map.put("econPictures", econPictures);
        map.put("input", auxiliaryDecision.getRfasi());
        map.put("critical", auxiliaryDecision.getEdcai());
        map.put("traffic", auxiliaryDecision.getTssAer());
        map.put("communications", auxiliaryDecision.getAssAer());
        map.put("power", auxiliaryDecision.getPssAer());
        map.put("important", auxiliaryDecision.getTmir());
        map.put("climate", auxiliaryDecision.getClimateCr());
        map.put("nation", auxiliaryDecision.getNationalCr());
        map.put("rumor", auxiliaryDecision.getTdwrapo());
        map.put("other", auxiliaryDecision.getOlftdwCr());

        return map;
    }

    /**
     * 去掉省或市   如山东省，报告中显示为山东；聊城市显示为聊城。
     */
    private String removeProvinceAndCity(String area, String subfix) {
        int areaIndex = area.lastIndexOf(subfix);
        if (areaIndex == area.length() - 1) {
            //避免出现省是名字的中间部分
            area = area.substring(0, areaIndex);
        }
        return area;
    }

    @Override
    public void downloadReport(String reportId, HttpServletResponse res) {
        AuxiliaryDecisionReport report = auxiliaryDecisionRepository.getReportById(reportId);
        String filePath = report.getReportPath();
        String fileName = report.getReportFactName();
        FileUploadUtil.download(filePath + File.separator + fileName, res);
    }

    @Override
    public Map<String, Object> getReport(String id) {
        AuxiliaryDecision auxiliaryDecision = auxiliaryDecisionRepository.findById(id);
        String reportId = auxiliaryDecision.getReportId();
        Map<String, Object> map = new HashMap<>(3);
        if (org.apache.commons.lang3.StringUtils.isBlank(reportId)) {
            map.put("attachId", "");
            map.put("reportName", "");
            map.put("reportId", "");
        } else {
            AuxiliaryDecisionReport report = auxiliaryDecisionRepository.getReportById(reportId);
            map.put("attachId", report.getAttachId());
            map.put("reportName", report.getReportName());
            map.put("reportId", report.getId());
        }
        return map;
    }

    @Override
    public DisasterScenario getDisasterScenario(String id) {
        AuxiliaryDecision byId = auxiliaryDecisionRepository.findById(id);
        if (PlatformObjectUtils.isEmpty(byId.getBuildingDamage())) {
            //获取地震信息
            RealEarthquakeEntity realEarthquakeEntity = simAnalyseRepository.getById(byId.getCataId());
            if (realEarthquakeEntity != null) {
                try {
                    String province = URLEncoder.encode(realEarthquakeEntity.getProvince(), "utf-8");
                    String city = URLEncoder.encode(realEarthquakeEntity.getCity(), "utf-8");
                    String county = URLEncoder.encode(realEarthquakeEntity.getCounty(), "utf-8");
                    String codeByCondition = sysAreaService.getIdByCondition(province, city, county);
                    Map<String,String> map= CreateGson.createGson().fromJson(redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY +
                            "areaIdCodeMap"),Map.class);

                    String codePrefix = map.get(codeByCondition.split("_")[2]);
                    // if(org.apache.commons.lang3.StringUtils.isNotBlank(codeByCondition)){
                    //     String[] codeList = codeByCondition.split("_");
                    //     if("北京市".equals(realEarthquakeEntity.getProvince()) || "上海市".equals(realEarthquakeEntity.getProvince()) ||
                    //             "天津市".equals(realEarthquakeEntity.getProvince()) || "重庆市".equals(realEarthquakeEntity.getProvince())){
                    //         codePrefix = codeList[0].substring(0,2)+"01";
                    //     }else{
                    //         if(codeList.length>1){
                    //             codePrefix = codeList[1].substring(0,4);
                    //         }
                    //     }
                    // }else{
                    //     return DisasterScenario.builder().build();
                    // }
                    if (org.apache.commons.lang3.StringUtils.isNotBlank(codePrefix)) {
                        ///调取实际地震震中影响场范围内烈度为VII度的区县信息
                        List<AreaResultVO> areaList = simAnalyseRepository.getAreaMessage(byId.getCataId(), codePrefix, Arrays.asList("6", "7", "8", "9", "10"));
                        //获取这些区县的灾害场景数据
                        if (PlatformObjectUtils.isNotEmpty(areaList)) {
                            List<String> collect = areaList.stream().map(AreaResultVO::getName).collect(Collectors.toList());
                            List<DisasterScenarioManageEntity> disasterScenarioManageAreaData = disasterScenarioManageRepository.getDisasterScenarioManageAreaData(realEarthquakeEntity.getProvince(),
                                    realEarthquakeEntity.getCity(), collect);
                            if (PlatformObjectUtils.isNotEmpty(disasterScenarioManageAreaData)) {
                                StringBuilder buildingDamage = new StringBuilder("");
                                StringBuilder casualties = new StringBuilder("");
                                StringBuilder geologicHazard = new StringBuilder("");
                                StringBuilder secondaryDisaster = new StringBuilder("");
                                StringBuilder earthquakeTraffic = new StringBuilder("");
                                StringBuilder otherDisaster = new StringBuilder("");
                                disasterScenarioManageAreaData.forEach(entity -> {
                                    buildingDamage.append(entity.getBuildingDamage()).append("。").append("\r\n");
                                    casualties.append(entity.getCasualties()).append("。").append("\r\n");
                                    geologicHazard.append(entity.getGeologicHazard()).append("。").append("\r\n");
                                    secondaryDisaster.append(entity.getSecondaryDisaster()).append("。").append("\r\n");
                                    earthquakeTraffic.append(entity.getEarthquakeTraffic()).append("。").append("\r\n");
                                    otherDisaster.append(entity.getOtherDisaster()).append("。").append("\r\n");
                                });
                                DisasterScenario disasterScenario = DisasterScenario.builder().buildingDamage(buildingDamage.toString())
                                        .casualties(casualties.toString()).geologicHazard(geologicHazard.toString()).secondaryDisaster(secondaryDisaster.toString())
                                        .earthquakeTraffic(earthquakeTraffic.toString()).otherDisaster(otherDisaster.toString()).build();
                                return disasterScenario;
                            } else {
                                return DisasterScenario.builder().build();
                            }
                        } else {
                            return DisasterScenario.builder().build();
                        }
                    } else {
                        return DisasterScenario.builder().build();
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
        DisasterScenario disasterScenario = DisasterScenario.builder().build();
        BeanUtils.copyProperties(byId, disasterScenario);
        return disasterScenario;

    }

    @Override
    public EmergencyResponse getEmergencyResponse(String id) {
        AuxiliaryDecision byId = auxiliaryDecisionRepository.findById(id);
        if (StringUtils.isEmpty(byId.getRfasi())){
            //获取地震信息
            RealEarthquakeEntity realEarthquakeEntity = simAnalyseRepository.getById(byId.getCataId());
            if(realEarthquakeEntity!=null){
                try{
                    String province = URLEncoder.encode(realEarthquakeEntity.getProvince(), "utf-8");
                    String city = URLEncoder.encode(realEarthquakeEntity.getCity(), "utf-8");
                    String county = URLEncoder.encode(realEarthquakeEntity.getCounty(), "utf-8");
                    String codeByCondition = sysAreaService.getIdByCondition(province, city, county);
                    Map<String,String> map= CreateGson.createGson().fromJson(redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY +
                            "areaIdCodeMap"),Map.class);

                    String codePrefix = map.get(codeByCondition.split("_")[2]);
                    // if(org.apache.commons.lang3.StringUtils.isNotBlank(codeByCondition)){
                    //     String[] codeList = codeByCondition.split("_");
                    //     if("北京市".equals(realEarthquakeEntity.getProvince()) || "上海市".equals(realEarthquakeEntity.getProvince()) ||
                    //             "天津市".equals(realEarthquakeEntity.getProvince()) || "重庆市".equals(realEarthquakeEntity.getProvince())){
                    //         codePrefix = codeList[0].substring(0,2)+"01";
                    //     }else{
                    //         if(codeList.length>1){
                    //             codePrefix = codeList[1].substring(0,4);
                    //         }
                    //     }
                    // }else{
                    //     return DisasterScenario.builder().build();
                    // }
                    if(org.apache.commons.lang3.StringUtils.isNotBlank(codePrefix)){
                        ///调取实际地震震中影响场范围内烈度为VII度的区县信息
                        String intensityList[] = {"7","8","9","10"};
                        List<AreaResultVO> areaList = simAnalyseRepository.getAreaMessage(byId.getCataId(),codePrefix,Arrays.asList(intensityList));
                        //获取这些区县的灾害场景数据
                        if(PlatformObjectUtils.isNotEmpty(areaList)){
                            List<String> collect = areaList.stream().map(AreaResultVO::getName).collect(Collectors.toList());
                            List<EmergencyDisposalManageEntity> emergencyDisposalManageAreaData = emergencyDisposalManageRepository.getEmergencyDisposalManage(realEarthquakeEntity.getProvince(),
                                    realEarthquakeEntity.getCity(), collect);
                            if(PlatformObjectUtils.isNotEmpty(emergencyDisposalManageAreaData)){
                                StringBuilder rescueForceMaterialInput = new StringBuilder("");
                                StringBuilder earthquakeDisasterCriticalArea = new StringBuilder("");
                                StringBuilder trafficSystemSupportRepair = new StringBuilder("");
                                StringBuilder communicationsSystemSupportRepair = new StringBuilder("");
                                StringBuilder powerSystemSupportRepair = new StringBuilder("");
                                StringBuilder importantFacilitiesCheck = new StringBuilder("");
                                StringBuilder climateFeatureReply = new StringBuilder("");
                                StringBuilder nationFeatureReply = new StringBuilder("");
                                StringBuilder rumorReply = new StringBuilder("");
                                StringBuilder otherFeatureReply = new StringBuilder("");
                                emergencyDisposalManageAreaData.forEach(entity->{
                                    rescueForceMaterialInput.append(entity.getRescueForceMaterialInput()).append("。").append("\r\n");
                                    earthquakeDisasterCriticalArea.append(entity.getEarthquakeDisasterCriticalArea()).append("。").append("\r\n");
                                    trafficSystemSupportRepair.append(entity.getTrafficSystemSupportRepair()).append("。").append("\r\n");
                                    communicationsSystemSupportRepair.append(entity.getCommunicationsSystemSupportRepair()).append("。").append("\r\n");
                                    powerSystemSupportRepair.append(entity.getPowerSystemSupportRepair()).append("。").append("\r\n");
                                    importantFacilitiesCheck.append(entity.getImportantFacilitiesCheck()).append("。").append("\r\n");
                                    climateFeatureReply.append(entity.getClimateFeatureReply()).append("。").append("\r\n");
                                    nationFeatureReply.append(entity.getNationFeatureReply()).append("。").append("\r\n");
                                    rumorReply.append(entity.getRumorReply()).append("。").append("\r\n");
                                    otherFeatureReply.append(entity.getOtherFeatureReply()).append("。").append("\r\n");
                                });
                                EmergencyResponse emergencyResponse = EmergencyResponse.builder().rfasi(rescueForceMaterialInput.toString())
                                        .edcai(earthquakeDisasterCriticalArea.toString()).tssAer(trafficSystemSupportRepair.toString()).assAer(communicationsSystemSupportRepair.toString())
                                        .pssAer(powerSystemSupportRepair.toString()).tmir(importantFacilitiesCheck.toString()).climateCr(climateFeatureReply.toString())
                                        .nationalCr(nationFeatureReply.toString()).tdwrapo(rumorReply.toString()).olftdwCr(otherFeatureReply.toString()).build();
                                return emergencyResponse;
                            }else{
                                return EmergencyResponse.builder().build();
                            }
                        }else{
                            return EmergencyResponse.builder().build();
                        }
                    }else{
                        return EmergencyResponse.builder().build();
                    }
                }catch (Exception ex){
                    ex.printStackTrace();
                }
            }
        }
        EmergencyResponse emergencyResponse = EmergencyResponse.builder().build();
        BeanUtils.copyProperties(byId,emergencyResponse);
        return emergencyResponse;
    }
}
